import api from "@/sdk/api/api.js"
export default {
	state:{
		cartList:[],
		all_active:false,
		allMoney:0.00,
	},
	mutations:{
		changeCartList(state,cartList){
			console.log(cartList);
			state.cartList = cartList
		},
		changeShopCartOnesSelect(state,index){
			let cartList = state.cartList;
			let cartInfo = cartList[index]
			if(cartInfo){
				if(cartInfo.selected&&cartInfo.selected==true){
					cartInfo.selected = false
				}else{
					cartInfo.selected = true;
				}
				cartList[index] = cartInfo
			}
			state.cartList = cartList;
			// console.log(state);
		},
		changeAllMoney(state){
			// console.log("haha");
			let cartList = state.cartList
			let money = 0;
			if(cartList.length>0){
				cartList.forEach(item=>{
					if(item&&item.selected&&item.selected==true){
						money += item.goodsitem.price*item.num
					}
				})
			}
			money = money.toFixed(2)
			state.allMoney = money
		},
		changeIsActive(state,bool){
			state.all_active = bool
		}
	},
	getters:{
		all_active:state=>{
			// console.log("计算属性");
			let all = true
			let cartList = state.cartList
			if(cartList.length==0){
				all = false
			}
			cartList.forEach(item=>{
				if(item.selected==false){
					all = false
				}
			})
			state.all_active = all
			return all;
		}
	},
	actions:{
		/**
		 * 获取所有的购物车
		 * @param {Object} context
		 */
		getCartList(context){
			let cartList = context.state.cartList;
			let newcart = {}
			if(cartList.length>0){
				cartList.forEach(item=>{
					newcart["index"+item.id] = item.selected;
				})
			}
			api.getShopCartList(false).then(res=>{
				res.forEach(item=>{
					if(newcart["index"+item.id]&&newcart["index"+item.id]==true){
						item.selected = true
					}else{
						item.selected = false
					}
				})
				context.commit("changeCartList",res);
				context.dispatch("countAllMoney")
			})
		},
		//重新计算全选和金额
		countAllMoney(context,index){
			context.commit("changeShopCartOnesSelect",index)
			context.commit("changeAllMoney")
		},
		//修改合计金额
		changeMoney(context){
			context.commit("changeAllMoney")
		},
		clckAllActive(context){
			let all_active = context.state.all_active;
			if(all_active==true){
				let cartList = context.state.cartList;
				cartList.forEach(item=>{
					item.selected = false;
				})
				context.commit("changeCartList",cartList)
				
			}else{
				let cartList = context.state.cartList;
				cartList.forEach(item=>{
					item.selected = true;
				})
				context.commit("changeCartList",cartList)
			}
			context.commit("changeAllMoney")
		}
	}
}